//
//  AdminAPI.swift
//  PerfectServer
//
//  Created by 王薰怡 on 2017/6/27.
//
//

import Foundation
import PerfectHTTP
import MySQL

struct AdminAPI: Reflectable {

    var apiRoutes: Routes {
        var routes = Routes()
        //MARK: - 接口路由
        routes.add(method: .post, uri: "/adminapi/login", handler: loginHandler(_:_:))
        return routes
    }
    
    
    //MARK: - 接口列表
    func loginHandler(_ request: HTTPRequest, _ response: HTTPResponse) {
        defer {
            response.completed()
        }
        guard let email = request.param(name: "email") else {
            response.appendBody(string: "Error: Email field is empty!")
            return
        }
        guard let password = request.param(name: "password") else {
            response.appendBody(string: "Error: Password field is empty!")
            return
        }
        guard let admin = AdminInfoDAO.findBy(email: email) else {
            response.appendBody(string: "Invalid email or password!")
            return
        }
        guard let md5Pwd = password.md5String,
            let pwd = (md5Pwd + admin.salt).sha256String else {
            response.appendBody(string: "Invalid email or password!")
            return
        }
        guard admin.password == pwd else {
            response.appendBody(string: "Invalid email or password!")
            return
        }
        response.appendBody(string: "Login Success")
    }

}
